<?php

namespace Contents\Related;

use Base\Contents;

/**
 * 相关内容组件(根据标签关联)
 *
 * @author edikud
 * @date 2022/10/22
 * @copyright Copyright (c) 2022 W3 (http://www.mcooo.com)
 * @license GNU General Public License 2.0
 */
class Related extends Contents
{
    /**
     * 初始化
     *
     * @access protected
     * @return void
     */
    protected function init()
    {
		# 定义变量默认数据
        $this->parameter([
		
		    'field' => '*',
			'type' => '',
			'tags' => '',
			'cid' => 0,
			'limit' => 5
			
		], true);
	}
	
    /**
     * 执行函数,初始化数据
     *
     * @access public
     * @return void
     */
    public function execute()
    {

		$tags = $this->parameter->tags;

        if (empty($tags)) {
			return ;
		}
		
		$cids = $this->db->select('table.relate.cid')
			->from('table.relate')
		    ->where('table.relate.mid = ?', array_rand($tags))
		    ->limit($this->parameter->limit + 1)
		    ->get();

        $cids = array_column($cids, 'cid');
        $key = array_search($this->parameter->cid, $cids);
        if($key !== false){  
            unset($cids[$key]);  
        } else {
		    array_pop($cids);
	    }

		if($cids){
	        $this->select($this->parameter->field)
				->where('table.contents.type = ?', $this->parameter->type)
				->where('table.contents.cid IN (' . substr( str_repeat( '?,', count( $cids ) ), 0, - 1 ) . ')', $cids)
			    ->get([$this, 'push']);
		}

    }
}
